package jpm;

import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.LinkOption;
import java.nio.file.Paths;
import java.util.List;

import jpm.common.JPMException;
import jpm.common.JPMException.ErrorCode;
import jpm.common.ListOfListBuilder;
import jpm.numbertriangle.NumberTriangle;

public class Main {

	public static void main(String[] args) {
		try {
			final String DEFAULT_INPUT_FILE = "input.csv";

			String inputFile = DEFAULT_INPUT_FILE;
			String messageIfFileMissing = "Cannot find ["
					+ DEFAULT_INPUT_FILE
					+ "] in current directory ["
					+ Paths.get("").toAbsolutePath()
					+ "] nor is any file specified through first command line parameter";

			if (args.length > 0) {
				inputFile = args[0];
				messageIfFileMissing = "Cannot find specified file ["
						+ inputFile + "]";
			}

			if (!Files.exists(Paths.get(inputFile), LinkOption.NOFOLLOW_LINKS))
				throw new JPMException().errorType(
						ErrorCode.ERROR_INVALID_INPUT).message(
						messageIfFileMissing);

			System.out.println("Reading [" + inputFile + "] ...");
			List<String> strings = Files.readAllLines(Paths.get(inputFile),
					Charset.defaultCharset());

			List<List<Integer>> listOfList = ListOfListBuilder.getBuilder()
					.append(strings, "\\s+").get();

			if (listOfList.isEmpty()) {
				System.out.println("[" + inputFile + "] is empty");
				return;
			}
			
			StopWatch sw = StopWatch.createStarted();
			int maxTotal = NumberTriangle.getMaxSum(listOfList);
			
			System.out.println("Max Total: " + maxTotal + " (computed in " + sw.nsElapsed() + " nanoseconds)");

		} catch (Exception ex) {
			if (ex instanceof JPMException) {
				JPMException jpmException = (JPMException) ex;
				System.out.println("Caught JPMException \nError type: "
						+ jpmException.getErrorCode() + "\nUser friendly message: "
						+ jpmException.getUserFriendlyMessage());
			} else
				System.out.println("Caught unhandled exception");

			System.out.println("\nStack trace:");
			ex.printStackTrace();
		}
	}
}
